package com.woniuxy.myshop.contrloller;

import com.woniuxy.myshop.entity.Address;
import com.woniuxy.myshop.entity.Product;
import com.woniuxy.myshop.entity.User;
import com.woniuxy.myshop.service.AddressService;
import com.woniuxy.myshop.service.CartService;
import com.woniuxy.myshop.service.ProductService;
import com.woniuxy.myshop.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    ////

    @Autowired
    CartService cartService ;

    @Autowired
    ProductService productService ;

    @Autowired
    AddressService addressService;

    //spring boot处理http请求有哪些注解？
    @GetMapping("/addCart/{id}")
    @ResponseBody
    public String addCart(@PathVariable(value = "id") int id, HttpSession session){
        User user = (User) session.getAttribute("userInfo");
        if (user == null){
            //凡没有登录
            return  "-1" ;
        }else {
            try{
                //验证 当前商品是否被添加过
                CartVo cart = cartService.queryCartByPidAndUserId(id,user.getId());
                if (cart == null){
                    cart = new CartVo();
                    //新添加的商品
                    //查询商品悐 根据id
                    Product p = productService.queryProductByKey(id);
                    cart.setBuycount(1);
                    cart.setProduct(p);
                    cart.setUser(user);

                    //做添加操作
                    cartService.addCart(cart);
                }else {
                    //已经添加过的商品  购买数量加 1
                    cartService.addBuyCount(id,user.getId());
                }
                return "1" ;
            }catch (RuntimeException e){
                e.printStackTrace();
            }
        }
        return "0" ;
    }

    @RequestMapping("/mycart")
    public String mycart(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("userInfo");
        if (user == null){
            request.setAttribute("errorInfo","请先登录!");
            return "login" ;
        }else {
            List<CartVo> list = cartService.queryMyCart(user.getId());
            request.setAttribute("list",list);

            //查询我的地址
            List<Address> alist = addressService.queryMyAddress(user.getId());
            request.setAttribute("alist",alist);
            return "cart" ;
        }
    }
}
